package com.lebang.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lebang.common.util.IpUtil;
import com.lebang.entity.ConfigurationRecord;
import com.lebang.entity.sys.LbbUser;
import com.lebang.mapper.LbbUserMapper;
import com.lebang.service.UserService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@Aspect
@Component
public class DataConfigAop {
    @Autowired
    private LbbUserMapper userMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Value("${info.appId}")
    private Integer APP_ID;

    @Pointcut("@annotation(com.lebang.aop.ConfigRecord)")
    public void pointCut() {
    }

    /**
     * 配置修改后写入Mongo
     * @param point
     * @param returnValue
     */
    @AfterReturning(value = "pointCut()", returning = "returnValue")
    public void after(JoinPoint point, Object returnValue) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            Object[] args = point.getArgs();
            String[] argNames = ((MethodSignature)point.getSignature()).getParameterNames();
            JSONObject json = (JSONObject) JSON.toJSON(returnValue);
            if (json.getBoolean("success")) {
                HttpSession session = request.getSession();
                String userId = (String) session.getAttribute("userid");
                LbbUser user = userMapper.getByUserId(userId);
                String ip = IpUtil.getIp(request);
                ConfigurationRecord configurationRecord=new ConfigurationRecord();
                configurationRecord.setCreateTime(LocalDateTime.now());
                configurationRecord.setModifyTime(LocalDateTime.now());
                configurationRecord.setOperator(user.getNickname());
                configurationRecord.setIp(ip);
                configurationRecord.setConfigName(args[0].getClass().getSimpleName());
                configurationRecord.setRecord(JSONObject.toJSONString(args[0]));
                configurationRecord.setAppId(APP_ID);
                mongoTemplate.insert(configurationRecord);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

